const db = require('../utils/mysql');
const moment = require('moment')
const md5 = require('md5');

class UserController {

    /**
     * 获取所有用户
     * @param req
     * @param res
     * @param next
     * @returns {Promise<void>}
     */
    async getAllUserInfo(req, res, next) {
        if (req.method === 'GET') {
            let sql = "SELECT `u_id`,`u_name`,`u_pwd`,`u_sex`,`u_status`,`u_createtime` FROM users;";
            let params = []

            try {
                let result = await db.exec(sql, params);
                if (result && result.length >= 1) {
                    res.json({
                        code: 200,
                        msg: "获取用户成功",
                        data: result
                    });
                } else {
                    res.json({
                        code: -200,
                        msg: '获取用户失败',
                    });
                }
            } catch (e) {
                res.json({
                    code: -201,
                    msg: '系统错误',
                    e
                });
            }
            // console.log("获取用户信息");
            // res.json({
            //     code:200,
            //     msg:"获取用户信息",
            // });
        }
    }

    /**
     * 通过ID获取用户
     * @param req
     * @param res
     * @returns {Promise<void>}
     */
    async getUserByID(req, res) {
        //获取Get方法参数 id
        // let {id,name} = req.query
        // console.log(id,name)
        let params = [
            parseInt(req.query.id),//字符转换成数字
        ]
        // console.log(typeof req.query.id)
        // console.log(typeof parseInt(req.query.id))
        let sqlStr = "SELECT `u_id`,`u_name`,`u_pwd`,`u_sex`,`u_status`," +
            "`u_createtime` FROM users where u_id = ?;";

        try {
            let result = await db.exec(sqlStr, params);
            if (result && result.length >= 1) {
                res.json({
                    code: 200,
                    msg: "获取用户成功",
                    data: result[0]
                })
            } else {
                res.json({
                    code: -200,
                    msg: "查询用户失败!查看数据是否存在"
                })
            }
        } catch (error) {
            res.json({
                code: -201,
                msg: "系统错误",
                error
            })
        }

        // res.json({
        //     code:200,
        //     msg:"我的提示信息"
        // });

    }

    /**
     * 通过ID删除用户
     * @param req
     * @param res
     * @returns {Promise<void>}
     */
    async deteleUserByID(req, res) {
        if (req.method === "GET") {
            console.log("处理GET方法")
            // res.send("处理GET方法")

            let params1 = [
                parseInt(req.query.id),
            ]
            let delSql = "delete from users where u_id=?;";
            try {
                let result = await db.exec(delSql, params1)
                if (result && result.affectedRows >= 1) {
                    res.json({
                        code: 200,
                        msg: "删除数据成功",
                        // data:result
                    })
                } else {
                    res.json({
                        code: -200,
                        msg: "删除数据失败，请查看数据",
                        // data:result
                    })
                }
            } catch (error) {
                res.json({
                    code: -400,
                    msg: "系统错误",
                    error
                })
            }
        } else {
            console.log("处理POST方法")
            // res.send("处理POST方法")
            let params = [
                parseInt(req.body.id),
            ]
            let delSql = "delete from users where u_id=?;";
            try {
                let result = await db.exec(delSql, params)
                if (result && result.affectedRows >= 1) {
                    res.json({
                        code: 200,
                        msg: "删除数据成功",
                        // data:result
                    })
                } else {
                    res.json({
                        code: -200,
                        msg: "删除数据失败，请查看数据",
                        // data:result
                    })
                }
            } catch (error) {
                res.json({
                    code: -400,
                    msg: "系统错误",
                    error
                })
            }
        }
    }

    /**
     * 通过ID更新用户数据
     * @param req
     * @param res
     * @returns {Promise<void>}
     */
    async updateUserByID(req, res) {
        let {id, name, pwd, sex, status,createtime} = req.body;
        console.log(id, name, pwd, sex, status)
        if (id == undefined) {
            res.json({
                code: -201,
                msg: "id为空"
            })
            return
        }

        // res.send("put 方法测试")

        let selSql = "SELECT `u_id`,`u_name`,`u_pwd`,`u_sex`,`u_status`," +
            "`u_createtime` FROM users where u_id = ?;";
        try {
            let result1 = await db.exec(selSql, [id]);
            if (result1 && result1.length >= 1) {
                // console.log(result1)
                if (name == undefined) {
                    name = result1[0]["u_name"]
                }

                if (pwd == undefined) {
                    pwd = result1[0]["u_pwd"]
                }else{
                    pwd = md5(pwd + require("../config").key)
                }

                if (status == undefined) {
                    pwd = result1[0]["u_status"]
                }

                // console.log(typeof result1)
                // console.log(result1[0]["u_name"])

                createtime = moment().format('YYYY-MM-DD HH:mm:ss')
            }
        } catch (error) {
            res.json({
                code: -201,
                msg: "请查看数据",
                error
            })
        }

        // res.send("put 方法测试")
        let updateSql = "UPDATE `users` SET `u_name`=?,`u_pwd`=?,`u_sex`=?," +
            "`u_status`=?,`u_createtime`=? WHERE `u_id`=?;";
        try {
            let up = await db.exec(updateSql, [name, pwd, sex, status, createtime, id])
            // console.log(up)
            if(up && up.affectedRows>0){
                res.json({
                    code: 200,
                    msg: "更新数据成功",
                    data:up
                })
            }else{
                res.json({
                    code: -201,
                    msg: "更新数据失败",
                    data:up
                })
            }

        } catch (error) {
            res.json({
                code: -201,
                msg: "系统错误，更新数据失败",
                error
            })
        }
    }

}

module.exports = new UserController();